
package nl.hanze.shoestring.ui;

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import nl.hanze.shoestring.domain.Continent;
import nl.hanze.shoestring.domain.Land;
import nl.hanze.shoestring.logic.Logic;

/** 
 * Beheer Land tabel
 * 
 * @author bleker
 */
public class LandPanel extends JPanel{
    
        Logic logic;
        JPanel pQueryInput, pRecord, pNavigation, pDbGrid;
        JLabel lblZoekSleutel, lblId, lblLandNaam, lblContinentNaam;
        JTextField txtZoekSleutel, txtId, txtLandNaam, txtContinentNaam;
        JButton butZoeken, butSave, butDelete, butEmpty;
        JComboBox cmbContinentNaam;
        JTable table;
        JScrollPane scrollPaneRes;
        DefaultTableModel model;
        Land landObj=null;
        List<Land> landList; 

        int heightField = 25;
        int numberOfRows = 22;

        public LandPanel(Logic logic) {
            this.logic = logic;
 
        table = new JTable();
        setLayout(new BorderLayout(20, 20));

        // input velden north sectie
        pQueryInput = new JPanel();
        pQueryInput.setLayout(null);
        pQueryInput.setPreferredSize(new Dimension(400, 60));
               

        lblZoekSleutel = UIHelper.createLabel(lblZoekSleutel = new JLabel(), "Zoeksleutel", 10, 10, 150, heightField, pQueryInput);
        txtZoekSleutel = UIHelper.createTextField(txtZoekSleutel = new JTextField(), "", 170, 10, 250, heightField, pQueryInput);

        txtZoekSleutel.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                searchLand();
            }
        
        });
        
        butZoeken = UIHelper.createButton(butZoeken = new JButton(), "Zoeken", 430, 10, 100, heightField, pQueryInput);
        butZoeken.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        searchLand();
                    }
                });

        // Center sectie, database record details
        pRecord = new JPanel();
        pRecord.setLayout(null);
        pRecord.setPreferredSize(new Dimension(400, 500));
        pRecord.setBorder(BorderFactory.createLineBorder(Color.blue));
        
        lblId = UIHelper.createLabel(lblId = new JLabel(), "Nummer", 20, 10, 150, heightField, pRecord);
        txtId = UIHelper.createTextField(txtId = new JTextField(), "", 170, 10, 100, heightField, pRecord);

        lblLandNaam = UIHelper.createLabel(lblLandNaam = new JLabel(), "Landnaam", 20, 70, 150, heightField, pRecord);
        txtLandNaam = UIHelper.createTextField(txtLandNaam = new JTextField(), "", 170, 70, 300, heightField, pRecord);

        lblContinentNaam = UIHelper.createLabel(lblContinentNaam = new JLabel(), "Continent", 20, 100, 150, heightField, pRecord);
        cmbContinentNaam = UIHelper.createCombo(cmbContinentNaam = new JComboBox(), 170, 100, 300, heightField, pRecord);
        fillComboFields();
 
        butSave = UIHelper.createButton(butSave = new JButton(), "Opslaan", 170, 150, 120, heightField, pRecord);
        butSave.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("save");
                        if(landObj!=null) {
                            updateRecord(landObj);
                        } else {
                            addRecord();
                        }
                    }
                });


        butDelete = UIHelper.createButton(butDelete = new JButton(), "Verwijderen", 350, 150, 120, heightField, pRecord);
        butDelete.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("delete");
                        if(landObj!=null) {
                            deleteRecord(landObj);
                        }
                }});
       
        butEmpty = UIHelper.createButton(butDelete = new JButton(), "Leeg/Nieuw", 350, 10, 120, heightField, pRecord);
        butEmpty.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        emptyAll();
                }});
        
        // fill tab pane
        add(pRecord, BorderLayout.CENTER);
        add(pQueryInput, BorderLayout.NORTH);
        addTable();
        emptyAll();
    }
        
        
    private void fillComboFields() {
        List<Continent> continent = logic.getContinentList();
        cmbContinentNaam.setModel(new DefaultComboBoxModel(continent.toArray()));
    }

    /**
     * Haal Land informatie uit database en toon in JTable
     */
    private void addTable() {

        // Gridcontainer
        pDbGrid = new JPanel(new BorderLayout(2, 3));

        // scroll pane eigenschappen
        scrollPaneRes = new JScrollPane(table);
        Dimension d = table.getPreferredSize();
        scrollPaneRes.setPreferredSize(new Dimension(d.width, table.getRowHeight() * numberOfRows));

        // navigatie container
        UIHelper.addNavigation(pNavigation = new JPanel(), table, scrollPaneRes, numberOfRows);
        
        // kolom eigenschappen - breedte
        Object[] headers = {"Nummer", "Land", "Continent"};
        int[] breedte = {100, 300, 300};
        
        // tablemodel en eigenschappen instellen, kolombreedte etc
        model = new DefaultTableModel(headers, 0) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
            // rendering van cellen, toont checkbox en juiste datum indien datatype overeenkomstig is
            // null velden veroorzaken fout, standaard maar op String gezet....
            @Override
            public Class getColumnClass(int column){
                try {
                 return getValueAt(0, column).getClass();
                } catch (java.lang.NullPointerException e) {
                    return String.class;
                }
            }

        };

        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        for (int i0 = 0; i0 < breedte.length; i0++) {
            table.getColumnModel().getColumn(i0).setPreferredWidth(breedte[i0]);
        }
        
        updateTable(true);
        
        // selecteer row door muisklik    
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                landObj = landList.get(table.convertRowIndexToModel(table.getSelectedRow()));
                getRecord(landObj);
            }
        });

        pDbGrid.add(scrollPaneRes, BorderLayout.CENTER);
        pDbGrid.add(pNavigation, BorderLayout.SOUTH);
        add(pDbGrid, BorderLayout.SOUTH);
    }
    
    
    /*
     *  Vul detailvelden met geselecteerde rowdata  
     */
    private void getRecord(Land landObj) {
        txtId.setText("" + landObj.getId());
        txtId.setEditable(false);
        txtLandNaam.setText("" + landObj.getNaam());
        cmbContinentNaam.setSelectedItem(landObj.getContinentId());
    }
    
    /*
     *  update record  
     */
    private void updateRecord(Land landObj) {
        landObj.setNaam(txtLandNaam.getText());
        landObj.setContinentId((Continent) cmbContinentNaam.getModel().getSelectedItem());
        logic.updateLand(landObj);
        updateTable(true);                
        emptyAll();
    }
    
    /*
     *  add new record  
     */
    private void addRecord() {
        landObj = new Land();
        landObj.setNaam(txtLandNaam.getText());
        landObj.setContinentId((Continent) cmbContinentNaam.getModel().getSelectedItem());
        logic.addLand(landObj);
        updateTable(true);                
        emptyAll();
    }

    /*
     *  delete record  
     */
    private void deleteRecord(Land landObj) {
        logic.deleteLand(landObj);
        updateTable(true);                
        emptyAll();
    }
    
    /*
     *  maak velden leeg en landObj =null  
     */
    private void emptyAll() {
        txtId.setEditable(false);
        txtId.setText("");
        txtLandNaam.setText("");
        cmbContinentNaam.setSelectedItem(null);
        landObj=null;
    }
    
    
    private void searchLand(){
        landList = logic.searchLand(txtZoekSleutel.getText());
        updateTable(false);                
    }
    
    private void updateTable(Boolean refresh) {
        if(refresh) {
            landList = logic.getLandList();
        }

        model.setRowCount(0);
        // data in JTable plaatsen
        for (Land land : landList) {
            Object[] o = {land.getId(),
                land.getNaam(),
                land.getContinentId().getNaam()};
            model.addRow(o);
        }
    }
}
